package com.mall.mallDemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.mallDemo.exception.ExceptionEnum;
import com.mall.mallDemo.exception.MyException;
import com.mall.mallDemo.mapper.UserMapper;
import com.mall.mallDemo.pojo.User;
import com.mall.mallDemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Lii
 * @create 2022-06-15 14:26
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    public User login(User user) {
//        user.setPassword(MD5Util.MD5Encode(user.getPassword() + "", "UTF-8"));
//
//
//        User one = userMapper.selectOne(user);
//        if (one == null) {
//            throw new MyException(ExceptionEnum.GET_USER_NOT_FOUND);
//        }
//        return one;
        String password = user.getPassword();
//        password = DigestUtils.md5DigestAsHex(DigestUtils.md5Digest(password.getBytes(StandardCharsets.UTF_8)));

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        User one = this.userMapper.selectOne(queryWrapper);

        if (one == null){
            throw new MyException(ExceptionEnum.USERNAME_NOT_EXISTS);
        }

        if (!one.getPassword().equals(password)){
            throw new MyException(ExceptionEnum.GET_USER_NOT_FOUND);
        }

        return one;
    }


    public void register(User user) {
        User one = new User();
        one.setUsername(user.getUsername());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        //用户名是否重复
        if (userMapper.selectCount(queryWrapper) == 1) {
            // 用户名已存在
            throw new MyException(ExceptionEnum.SAVE_USER_REUSE);
        }
//        user.setPassword(MD5Util.MD5Encode(user.getPassword() + "", "UTF-8"));
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(ExceptionEnum.SAVE_USER_ERROR);
        }
    }

    public void isUserName(String username) {
        User one = new User();
        one.setUsername(username);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        if (userMapper.selectCount(queryWrapper) == 1) {
            throw new MyException(ExceptionEnum.SAVE_USER_REUSE);
        }
    }
}
